package service

import (
	"chat/global"
	"chat/internal/model"
)

func GetAllGroup(id int) ([]model.Group, error) {
	var groups []model.Group
	err := global.DB.Raw("select `groups`.* from `groups` inner join group_members gm on `groups`.id = gm.group_id where gm.user_id = ?", id).Scan(&groups).Error
	return groups, err
}

func GetGroupsChatInfoByUserId(uid int) ([]model.Group, error) {
	var groups []model.Group
	err := global.DB.Raw("select g.* from group_members inner join `groups` g on group_members.group_id = g.id where group_members.user_id = ?", uid).Scan(&groups).Error
	return groups, err
}

func GetGroupCntByGroupId(id int) (int, error) {
	r := 0
	err := global.DB.Raw("select count(*) from `groups` where id = ?", id).Scan(&r).Error
	return r, err
}

func GetGroup(g model.Group) (int, error) {
	n := 0
	err := global.DB.Raw("select count(*) from `groups` where user_id = ? and name = ?", g.UserId, g.Name).Scan(&n).Error
	return n, err
}

func CreateGroup(g *model.Group) error {
	return global.DB.Create(&g).Error
}

func GetGroupById(id int) (model.Group, error) {
	var g model.Group
	err := global.DB.Where("id = ?", id).Find(&g).Error
	return g, err
}

func UpdateGroupName(gId int, name string) error {
	return global.DB.Exec("update `groups` set name = ? where id = ?", name, gId).Error
}

func UpdateGroupNotice(gId int, notice string) error {
	return global.DB.Exec("update `groups` set notice = ? where id = ?", notice, gId).Error
}
